package study.springcloud.hystrix.controller;

import cn.hutool.core.thread.ThreadUtil;
import com.google.common.base.Stopwatch;
import com.google.common.collect.Maps;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import study.eggs.result.Result;
import study.eggs.result.Results;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/fallback")
public class _02_FallbackController {

    @HystrixCommand(fallbackMethod = "throwExByFallback")
    @RequestMapping("/throw_ex")
    public Result throwEx(String throwEx) {
        Stopwatch stopwatch = Stopwatch.createStarted();
        log.info(">>>>>> fallback start");
        if ("1".equals(throwEx)) {
            throw new RuntimeException("抛出异常");
        }
        log.info(">>>>>> fallback cost time [{}] ms", stopwatch.elapsed(TimeUnit.MILLISECONDS));
        return Results.ok();
    }

    public Result throwExByFallback(String throwEx) {
        Map<String, Object> data = Maps.newHashMap();
        data.put("throwEx", throwEx);
        data.put("message", "抛出异常");
        return Results.ok(data);
    }

    @HystrixCommand(fallbackMethod = "timeoutByFallback")
    @RequestMapping("/timeout")
    public Result timeout(long timeout) {
        Stopwatch stopwatch = Stopwatch.createStarted();
        log.info(">>>>>> timeout start");
        ThreadUtil.sleep(timeout, TimeUnit.SECONDS);
        log.info(">>>>>> timeout cost time [{}] ms", stopwatch.elapsed(TimeUnit.MILLISECONDS));
        return Results.ok();
    }

    public Result timeoutByFallback(long timeout) {
        Map<String, Object> data = Maps.newHashMap();
        data.put("timeout", timeout);
        data.put("message", "执行超时");
        return Results.ok(data);
    }
}
